package Volume1.ch10;

import javax.swing.*;
import java.awt.*;

/**
 * 10-6：绘制图像demo
 * @Auther jacob
 * @Date 2020/8/16 02:08
 */
public class ImageTest {
    public static void main(String[] args) {
        EventQueue.invokeLater(()->{
            JFrame frame = new ImageFrame();
            frame.setTitle("ImageTest");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setVisible(true);
        });
    }
}

class ImageFrame extends JFrame{
    public ImageFrame(){
        add(new ImageComponent());
        pack();
    }
}

class ImageComponent extends JComponent{
    public static final int DEFAULT_WIDTH = 500;
    public static final int DEFAULT_HEIGHT = 500;

    private Image image;

    public ImageComponent() {
        image = new ImageIcon("src/source/tom.png").getImage();
    }

    @Override
    public void paintComponent(Graphics g){
        if (image == null){
            System.out.println("image is null");
        }

        int width = image.getWidth(this);
        int height = image.getHeight(this);

        // draw thw image in the upper-left corner
        g.drawImage(image, 0, 0, null);

        // tile the image across the component
        for (int i = 0; i * width <= getWidth(); i++) {
            for (int j = 0; j * height <= getHeight(); j++) {
                if (i + j > 0){
                    g.copyArea(0, 0, width, height, i*width, j*height);
                }
            }
        }
    }


    @Override
    public Dimension getPreferredSize() {
        return new Dimension(DEFAULT_WIDTH, DEFAULT_HEIGHT);
    }
}
